package com.atguigu.tingshu.search.receiver;

import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.search.service.SearchService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class SearchReceiver {
 @Autowired
    private SearchService searchService;

 /**
  * 监听MQ的队列，用于处理相册提升操作
  * 当相册相关的操作完成后，通过此函数通知系统进行相册的提升处理
  *
  * @param albumId 相册ID，标识需要进行提升操作的相册
  * @param message MQ中的消息内容
  * @param channel MQ通道，用于确认消息接收成功
  */
 @RabbitListener(bindings = @QueueBinding(
     exchange = @Exchange(value = MqConst.QUEUE_ALBUM_UPPER, durable = "true"),
     value = @Queue(value = MqConst.QUEUE_ALBUM_UPPER, durable = "true"),
     key = {MqConst.ROUTING_ALBUM_UPPER}))
 public void upperAlbum(Long albumId, Message message, Channel channel) {
     // 当相册ID为null时，调用searchService的upperAlbum方法进行处理
     // 这里处理的情况是相册ID为null时的特殊情况，可能是因为系统默认需要处理所有相册的情况
     if (null == albumId) {
         searchService.upperAlbum(albumId);
     }
     // 手动确认消息接收成功
     // 使用try-catch块来捕获并处理可能的IOException，确保消息确认过程的异常能够被捕捉并抛出运行时异常
     try {
         channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
     } catch (IOException e) {
         throw new RuntimeException(e);
     }
 }
 @RabbitListener
         (bindings = @QueueBinding(exchange = @Exchange(value = MqConst.QUEUE_ALBUM_LOWER,durable = "true"),
          value=@Queue(value = MqConst.QUEUE_ALBUM_LOWER,durable = "true"),
         key={MqConst.ROUTING_ALBUM_LOWER}))
 public void lowerAlbum(Long albumId,Message message,Channel channel)
 {
     if (null==albumId){
         searchService.lowerAlbum(albumId);
     }
     try {
         channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
     } catch (IOException e) {
         throw new RuntimeException(e);
     }
 }

}
